package socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;


public class Server {
	public static void main(String[] args) throws Exception {
		try {
			testServer();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
//	    // 监听指定的端口
//	    int port = 55533;
//	    ServerSocket server = new ServerSocket(port);
//	    
//	    // server将一直等待连接的到来
//	    System.out.println("====== Server 服务器已经开启 =======\n");
//	    System.out.println("server将一直等待连接请求的到来");
//	    long c1 = System.currentTimeMillis();
//	    Socket socket = server.accept();
//	    long c2 = System.currentTimeMillis();
//	    System.out.println("====== Server 服务器已获得连接,用时["+ (c2-c1) + "]=======\n");
//	    
//	    // 建立好连接后，从socket中获取输入流，并建立缓冲区进行读取
//	    InputStream inputStream = socket.getInputStream();
//	    byte[] bytes = new byte[1024];
//	    int len;
//	    StringBuilder sb = new StringBuilder();
//	    while ((len = inputStream.read(bytes)) != -1) {
//	      //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
//	      sb.append(new String(bytes, 0, len,"UTF-8"));
//	    }
//	    
//	    System.out.println("====== Server 服务器已经获取数据 =======\n");
//	    System.out.println("get message from client: " + sb);
//	    
//	    
//	    // 建立连接后获得输出流
//	    System.out.println("====== Server 服务器即将发送数据 =======\n");
//	    String message = "你好  sb";
//	    socket.getOutputStream().write(message.getBytes("UTF-8"));
//	    //通过shutdownOutput通知服务器已经发送完数据，后续只能接受数据
//	    socket.shutdownOutput();
//	    
//	    
//	    System.out.println("====== Server 服务器通信结束，即将断开socket连接 =======\n");
//	    // inputStream.close()和output都要放在最后，若提取释放，将会报错，提示socket断开
//	    inputStream.close();
//	    socket.close();
//	    server.close();
	  }
	
	public static void  testServer() throws IOException {
		int port = 12345;
		ServerSocket ss = new ServerSocket(port);
		System.out.println("====== Server 服务器已start =======\n");
		
		Socket so = ss.accept();
		System.out.println("====== Server 服务器已获得连接 =======\n");
		
		InetAddress inetAddress = so.getInetAddress();
		System.out.println(inetAddress.toString());
		InputStream inputStream = so.getInputStream();
		
		byte[] bytes = new byte[512];
		int len;
	    StringBuilder sb = new StringBuilder();
	    while ((len = inputStream.read(bytes)) != -1) {
	      sb.append(new String(bytes, 0, len,"UTF-8"));
	    }
	    so.shutdownInput();
	    System.out.println("====== Server 服务器已经获取数据 =======\n");
	    System.out.println(sb.toString());
		
	    OutputStream outputStream = so.getOutputStream();
	    outputStream.write("1www我是123".getBytes("UTF-8"));
	    //通过shutdownOutput通知服务器已经发送完数据，后续只能接受数据
	    so.shutdownOutput();
	    
	    so.close();
	    ss.close();	
	    System.out.println("====== Server 服务器通信结束断开连接 =======\n");
	}
}
